package com.lapelife.backend.service.impl;

import com.lapelife.backend.mapper.SysMenuMapper;
import com.lapelife.backend.mapper.SysUserMapper;
import com.lapelife.backend.domain.entity.LoginUser;
import com.lapelife.backend.domain.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

@Component
public class UserDetailServiceImpl implements UserDetailsService {
    private SysUserMapper sysUserMapper;

    private SysMenuMapper sysMenuMapper;

    @Autowired
    public void setSysUserMapper(SysUserMapper sysUserMapper) {
        this.sysUserMapper = sysUserMapper;
    }

    @Autowired
    public void setSysMenuMapper(SysMenuMapper sysMenuMapper) {
        this.sysMenuMapper = sysMenuMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (!StringUtils.hasText(username)) {
            throw new RuntimeException("用户名或密码错误");
        }
        // 从数据库查询用户
        SysUser sysUser = sysUserMapper.selectOneByUserName(username);
        if (Objects.isNull(sysUser)) {
            throw new RuntimeException("用户不存在");
        }
        // 获取用户权限
        List<String> list = sysMenuMapper.selectPermsByUserId(sysUser.getUserId());
        return new LoginUser(sysUser,list);
    }
}
